<template>
  <div>
    <template v-if="fromVip">
    <!-- 高级审批开始 -->
            <advanced-approval-process
              :approveData="approveData"
              :approveId="approveId"
              :approveObject="approve"
              module="event"
              ref="advancedApprovalProcessRef"
              @update="refresh"
            >
            </advanced-approval-process>
          <!-- 高级审批结束 -->
    <!-- <div slot="footer" class="dialog-footer">
      <template v-if="fromVip">
            <el-button
              v-if="vipBtnSetting.cnName"
              type="primary"
              plain
              :disabled="pending"
              @click="openEventAdvancedApprove"
            >
              {{ vipBtnSetting.cnName }}
            </el-button>
          </template>
    </div> -->
    </template>
    <base-modal :title="$t('event.detail.components.dialog.text27')" width="500px" :show.sync="visible" v-else>
      <div class="base-modal-content task-advanced-approve">
        <div class="signature-advise">
          <div class='nameAndAction'>
          <div class="form-view-row">
            <label>{{$t('common.base.promoter')}}</label>
            <div class="form-view-row-content">
              <template v-if="isOpenData && approve.proposerStaffId">
                <open-data type="userName" :openid="approve.proposerStaffId"></open-data>
              </template>
              <template v-else>
                {{ approve.proposerName }}
              </template>
            </div>
          </div>
          <div class="form-view-row">
            <label>{{$t('common.base.node')}}</label>
            <div class="form-view-row-content">{{ getApproveActionLabel(approve.action) }}</div>
          </div>
        </div>

        <!-- 指派时显示负责人和协同人 start -->
        <div class='nameAndAction' v-if="otherInfo.action == '分配'">
          <div class="form-view-row">
            <label>{{$t('task.executor')}}</label>
            <div class="form-view-row-content">
              <template v-if="isOpenData && executor.staffId">
                <open-data type="userName" :openid="executor.staffId"></open-data>
              </template>
              <template v-else>
                {{ executor.displayName }}
              </template>
            </div>
          </div>
          <div class="form-view-row">
            <label>{{$t('task.synergies')}}</label>
            <div class="form-view-row-content">
              <template v-if="isOpenData && synergies">
                <open-data v-for="item in synergies" type="userName" :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                {{ synergies.map(item => item.displayName).join(',') }}
              </template>
            </div>
          </div>
        </div>
        <!-- 指派时显示负责人和协同人 end -->
        
        <div class="form-view-row">
          <label>{{$t('task.promoteTime')}}</label>
          <div class="form-view-row-content">{{ approve.createTime | fmt_datetime }}</div>
        </div>
        <div class="form-view-row">
          <label>{{$t('task.promoteRemark')}}</label>
          <div class="form-view-row-content">{{ atTextToHtml1(approve.applyRemark) }}</div>
        </div>
        </div>
        <template>
          <!--S 一级审批 -->
          <template v-if="configLevel === 1">
            <!-- <div class="form-view-row">
              <label>审批结果：</label>
              <div class="form-view-row-content result-content">
                <el-radio-group v-model="result">
                  <el-radio label="success">通过</el-radio>
                  <el-radio label="fail">拒绝</el-radio>
                </el-radio-group>
              </div>
            </div> -->
            <div class="form-view-row">
              <label><span style="color:red" v-if="approveUserRemark">*</span>{{$t('task.detail.components.approveResult')}}</label>
              <div class="form-view-row-content form-view-row-content-textarea">
                <!-- <textarea v-model="approveRemark" placeholder="请输入审批结果[最多500字]" rows="3" maxlength="500" /> -->
                <biz-at-textarea class="biz-at-textarea" ref="atTextarea" search-url="/message/user/lists" name-key="displayName" v-model="approveRemark" :at-users.sync="atUsers">
                  <template slot="item" slot-scope="item">
                    <img :src="head(item.user.head)">
                    <span>{{item.user.displayName}}</span>
                  </template>
                  <textarea ref="editor" class="base-at-textarea" @input="inputContent" :placeholder="$t('event.detail.components.dialog.text28')" maxlength="500" :rows="3"></textarea>
                </biz-at-textarea>
                <p class="tips">{{$t('contract.approveDialog.form.tip')}}</p>
              </div>
            </div>
          </template>
          <!--E 一级审批 -->
          <!-- S 多级审批 -->
          <el-steps v-else class="approve-steps" direction="vertical">
            <!--S 已经审批的步骤 -->
            <el-step class="approve-step-item" v-for="(item, idx) in approve.approverResult" :key="idx" status="success">
              <el-row slot="title" type="flex" justify="space-between">
                <h2 class="pass">
                  {{$t('common.base.approveLevel', {data1: formatNumToCN(idx + 1)})}}  <span>{{$t('common.base.through')}}</span>
                </h2>
                <p style="color: rgba(0, 0, 0, 0.45)">{{item.completeTime | fmt_datetime}}</p>
              </el-row>
              <div class="approve-step-item-desc" slot="description">
                <label>{{$t('common.base.approveUser')}}： </label>
                <template v-if="isOpenData && item.approverStaffId">
                  <open-data type="userName" :openid="item.approverStaffId"></open-data>
                </template>
                <template v-else>
                  {{ getApproversLabel(item.approverName) }}
                </template>
                <p>{{$t('task.detail.components.approveSuggestion')}}： {{atTextToHtml1(item.approveRemark)}}</p>
              </div>
            </el-step>
            <!--E 已经审批的步骤 -->
            <!--S 当前审批的步骤 -->
            <el-step class="approve-step-item" status="process">
              <el-row slot="title" type="flex" justify="space-between">
                <h2>{{$t('event.detail.components.dialog.text25', {data1: formatNumToCN(approve.approverResult.length + 1)})}}</h2>
              </el-row>
              <div class="approve-step-item-desc" slot="description">
                <label>{{$t('common.base.approveUser')}}： </label>
                <template v-if="isOpenData && approve.approvers && approve.approvers.length">
                  <open-data v-for="item in approve.approvers" :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                </template>
                <template v-else>
                  {{ approve.approvers | formatApproveNames}}
                </template>
  
                <el-row type="flex">
                  <label><span style="color:red" v-if="approveUserRemark">*</span>{{$t('task.detail.components.approveResult')}}：</label>
                </el-row>
                <!-- <textarea v-model="approveRemark" placeholder="请输入审批结果[最多500字]" rows="3" maxlength="500" /> -->
                <biz-at-textarea class="biz-at-textarea" ref="atTextarea" search-url="/message/user/lists" name-key="displayName" v-model="approveRemark" :at-users.sync="atUsers">
                  <template slot="item" slot-scope="item">
                    <img :src="head(item.user.head)">
                    <span>{{item.user.displayName}}</span>
                  </template>
                  <textarea ref="editor" class="base-at-textarea" @input="inputContent" :placeholder="$t('event.detail.components.dialog.text28')" maxlength="500" :rows="3"></textarea>
                </biz-at-textarea>
                <p class="tips">{{$t('event.detail.components.dialog.text26')}}</p>
              </div>
            </el-step>
            <!--E 当前审批的步骤 -->
            <!--S 未到审批的步骤 -->
            <el-step class="approve-step-item" v-for="(item, idx) in approve.multiApprover" :key="idx" status="wait">
              <el-row slot="title" type="flex" justify="space-between">
                <h2>{{$t('common.base.approveLevel', {data1: formatNumToCN(approve.approverResult.length + idx + 2)})}}</h2>
              </el-row>
              <div class="approve-step-item-desc" slot="description">
                <label>{{$t('common.base.approveUser')}}： </label>
                <template v-if="isOpenData && item && item.length">
                  <open-data v-for="approve in item" :key="approve.staffId" type="userName" :openid="approve.staffId"></open-data>
                </template>
                <template v-else>
                  {{ item | formatApproveNames}}
                </template>
              </div>
            </el-step>
            <!--E 未到审批的步骤 -->
          </el-steps>
          <!-- E 多级审批 -->
        </template>
      </div>
      <div slot="footer" class="dialog-footer">
        <div class="dialog-footer-left"></div>
        <div class="dialog-footer-right">
          <template>
            <el-button :disabled="pending" @click='visible = false'>{{$t('common.base.cancel')}}</el-button>
            <el-button type="danger" @click="submit('fail')" :disabled="pending" v-if='btnType == "refuse"'>{{$t('common.base.refuse')}}</el-button>
            <el-button type="primary" @click="submit('success')" :disabled="pending" v-if='btnType == "agree"'>{{$t('common.base.agree')}}</el-button>
          </template>
        </div>
      </div>
    </base-modal>
    
  </div>
</template>

<script>
/* components*/
import AdvancedApprovalProcess from '@src/component/compomentV2/AdvancedApproval/compoment/AdvancedApprovalProcess.vue';
import { isOpenData } from '@src/util/platform'
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import { getApproveLoadForEvent } from '@src/api/EventApi'
/* enum */
import { ApproveActionLabelEnum, EventApproversLabelEnum } from '@model/enum/LabelEnum.ts'
import { getRootWindow } from '@src/util/dom'
import { getOssUrl } from '@src/util/assets'
import {enCodeAtText, getReceivers, atTextToHtml1} from '@src/util/atText'
import { cutAtTextContent } from 'pub-bbx-utils'
import { useTenantId, useRootUser } from '@hooks/useRootWindow.ts';
import i18n from '@src/locales';

const defaultAvatar = getOssUrl('/avatar.png')
const rootWindow = getRootWindow(window)
const $t = i18n.t.bind(i18n);

export default {
  name: 'event-approve-dialog',
  props: {
    approveId: {
      type: String,
      default: '',
    },
    taskId: {
      type: String,
      default: '',
    },
    eventId: {
      type: String,
      default: '',
    },
    approveUserRemark:{
      type: Boolean,
      default: false,
    }
  },
  data: () => {
    return {
      isOpenData,
      visible: false,
      loading: false,
      atUsers:[],
      pending: false,
      approve: {},
      approveRemark: '',
      currLevel: 1, // 当前审批层级
      approveContentStr: '',
      otherInfo: {},
      atTextToHtml1,
      // 高级审批参数
      fromVip: false,
      approveData: {},
      vipBtnSetting: {}, // 高级审批按钮设置
      btnType: '',
    };
  },
  components: {
    AdvancedApprovalProcess,
  },
  computed: {
    // 分配负责人
    executor() {
      return this.otherInfo?.executor || {}
    },
    // 分配协同人
    synergies() {
      return this.otherInfo?.synergies || []
    },
    configLevel() {
      return this.approve.otherInfo && this.approve.otherInfo.params && this.approve.otherInfo.params.level || 1;
    },
    showApproveReason() {
      return ['暂停', '取消'].includes(this.approve?.action)
    }
  },
  filters: {
    formatApproveNames(approvers) {
      return approvers.map(item => item.displayName).join(',') || $t('task.tip.approveTip3');
    },
    formatSynergiesNames(synergies) {
      if(synergies) return synergies.map(item => item.displayName).join(',') || '';
      return ''  
    }
  },
  mounted () {
    this.approveContentStr = this.approveContent()
    this.$nextTick(()=> {
      if(rootWindow.WWOpenData) {
        rootWindow.WWOpenData.bindAll(document.querySelectorAll('ww-open-data'));
      }
    })
  },
  methods: {
    // 获取审批人多语言label
    getApproversLabel(name) {
      return EventApproversLabelEnum[name] || name
    },
    head(src) {
      if (!src) return defaultAvatar
      return src
    },
    inputContent(event){
      let value = event.target.value;
      this.approveRemark = value;
    },
    goApproveDetail() {

      window.location.href = `${this.$resourcePrefix}/task/view/${this.taskId}?isToReceiptView=true`
    },
    formatNumToCN(num) {
      let changeNum = [
        this.$t('common.base.number0'),
        this.$t('common.base.number1'),
        this.$t('common.base.number2'),
        this.$t('common.base.number3'),
        this.$t('common.base.number4'),
        this.$t('common.base.number5'),
        this.$t('common.base.number6'),
        this.$t('common.base.number7'),
        this.$t('common.base.number8'),
        this.$t('common.base.number9')
      ];
      return changeNum[num];
    },
    reset() {
      this.approveRemark = '';
      this.approve = {};
      this.atUsers = []
    },
    openDialog(btnType) {
      
      this.btnType = btnType

      if (this.pending) return;
      this.pending = true;

      // 重置
      this.reset();

      TaskApi.getApprove({ id: this.approveId })
        .then((res) => {
          if (res.status == 0) {
            if (res.data?.processorInstanceId) {
              this.fromVip = true
              this.approve = res.data;
              this.otherInfo = this.approve.otherInfo.params;
              this.getVipData(btnType)
            } else {
              this.approve = res.data;
              this.otherInfo = this.approve.otherInfo.params;
              this.visible = true;
              this.currLevel = res.data.approverLevel;
            }
          } else {
            this.$platform.alert(res.message);
          }
        })
        .catch((err) => console.log(err))
        .finally(() => {
          this.pending = false;
        })
    },
    async getVipData(btnType) {
      try {
        const { success, result } = await getApproveLoadForEvent({approveId: this.approveId})

        if(!success) return;

        this.approveData = result;

        this.vipBtnSetting = ((result?.approveInfo?.buttons || []).filter((item) => item.enName === btnType))?.[0] || {}
        setTimeout( () => {

          // this.visible = true;
          this.$refs.advancedApprovalProcessRef.openDialog(this.btnType, [], {
            objid: this.approve.objId,
            objno: this.approve.objNo
          })
        },500)


      } catch (e) {
        console.error(e)
      }
    },

    refresh() {
      window.location.href = `${this.$resourcePrefix}/event/view/${this.eventId}`;
    },

    openEventAdvancedApprove() {
      this.$refs.advancedApprovalProcessRef.openDialog(this.btnType, [], {
        objid: this.approve.objId,
        objno: this.approve.objNo
      })
    },

    submit(result) {
      let { approveId, approveRemark } = this;
      // approveUserRemark 是由系统设置->工单设置->审批备注设置->审批人员审批是否必填备注信息 选项控制
      if(this.approveUserRemark && !approveRemark){ 
        return this.$platform.notification({ type: 'error', title: this.$t('task.tip.approveTip4')})
      } 
      let receivers = ''
      let query = ''
      let remark = approveRemark
      if(approveRemark){
        remark = enCodeAtText(approveRemark, this.atUsers);
        receivers = getReceivers(approveRemark, this.atUsers)
        let queryData = {
          receivers,
          tenantId: useTenantId().value,
          content: cutAtTextContent(approveRemark),
          sendUserName: useRootUser().value?.displayName,
          bizId: this.approve.objId,
          bizNo: this.approve.objNo,
          md:'event'
        };
        query = '?';
        for (let i in queryData) {
          query += `&${i}=${queryData[i]}`;
        }
      }
      this.pending = true;
      TaskApi.saveApprove({ id: approveId, result, approveRemark:remark, currLevel: this.currLevel || 1 }, query)
        .then((res) => {
          if (res.status == 0) {
            this.$platform.notification({
              type: 'success',
              title: this.$t('common.base.approveSuccess')
            })

            let fromId = window.frameElement.getAttribute('fromid');
            this.$platform.refreshTab(fromId);
            if(this.approve.source == 'task'){
              window.location.href = `${this.$resourcePrefix}/task/view/${this.taskId}`;
            }else {
              window.location.href = `${this.$resourcePrefix}/event/view/${this.eventId}`;
            }
          } else {
            this.$platform.alert(res.message);
            this.pending = false;
          }
        })
        .catch((err) => {
          this.pending = false;
        });
    },
    // 处理审批时相关展示的内容
    approveContent() {
      try {
        let otherInfo = this.approve?.otherInfo?.params || {};
        if (this.approve.source == 'task') {
          if (this.approve.action == '指派') {
            if (otherInfo.auto) return this.$t('common.event.actionStatus.autoDispatch');
            if (otherInfo.toPool) return this.$t('task.detail.components.publishToTaskPool');

            let executor = JSON.parse(otherInfo.taskJson).executor || {};
            return this.$t('task.detail.components.allotTo') + `${ this.isOpenData ? `<ww-open-data type="userName" openid="${executor.staffId}"></ww-open-data>` : executor.displayName}`;
          }

          if (this.approve.action == '转派') {
            let executor = JSON.parse(otherInfo.taskJson).executor || {};
            return this.$t('task.detail.components.transferTo') + `${ this.isOpenData ? `<ww-open-data type="userName" openid="${executor.staffId}"></ww-open-data>` : executor.displayName}`;
          }

          if (this.approve.action == '完成') {
            return this.$t('event.detail.components.dialog.text29');
          }

          if (this.approve.action == '结算') {
            return this.$t('event.detail.components.dialog.text30');
          }

          if (this.approve.action == '回访') {
            return this.$t('event.detail.components.dialog.text31');
          }

          if (this.approve.action == '暂停') {
            return otherInfo.reason;
          }

          if (this.approve.action == '取消') {
            let content = JSON.parse(otherInfo.contentJson).updateContent;
            return `${content}`;
          }

          return '';
        }

        if (this.approve.source == 'event') {
          if (this.approve.action == '分配') {
            return this.$t('task.detail.components.assignTo') + `${ this.isOpenData ? `<ww-open-data type="userName" openid="${otherInfo.executorStaffId}"></ww-open-data>` : otherInfo.executorName}`;
          }

          if (this.approve.action == '完成') {
            return this.$t('event.detail.components.dialog.text32');
          }

          if (this.approve.action == '暂停') {
            return otherInfo.reason;
          }

          return '';
        }
      } catch (err) {
        console.error('approveContent error', err);
      }
    },
    // 获取action的多语言label
    getApproveActionLabel(key) {
      return ApproveActionLabelEnum[key] || key
    },
  }
}
</script>

<style lang="scss">
.task-approve-dialog {
  .form-view-row {
    padding: 6px 0px;
    label{
      min-width: 84px;
      text-align: left;
    }

    .result-content {
      height: 24px;
      overflow-y: hidden;
    }
  }

  .dialog-footer {
    text-align: left;
    display: flex;
    flex: 1;

    .dialog-footer-left {
      flex: 1;
      font-size: 12px;
    }

    .dialog-footer-right {
      text-align: right;
    }
  }
}
 .layx-window .base-window-content textarea {
  width: 100% !important;
}
</style>

<style lang="scss" scoped>
.dividing-line{
  margin-top: 4px;
  width: calc(100% + 38px);
  border-top: 1px #ddd dashed;
  transform: translateX(-20px);
}

.tips {
  margin-bottom: 0!important;
  margin-top: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.go-approve-detail {
  color: $color-primary-light-6;
  text-decoration: underline;
}
.approve-reason-new {
  padding: 12px 16px;
  margin-left: 112px;
  border-radius: 4px;
  background-color: #f5f5f5;
  .reason-label {
    width: 72px;
  }
}
.approve-steps{
  padding-top: 20px;
  .approve-step-item{
    color: #000000;
    h2{
      font-size: 14px;
      color: #262626;
      &.pass span{
        color: #52C41A;
      }
    }
    &-desc{
      padding: 12px;
      background: #FAFAFA;
    }
  }
}

// element-ui
::v-deep .el-step__main{
  margin-bottom: 20px;
}
::v-deep .el-step__description{
  color: #000000;
  padding: 0
}
.form-view-row-content-textarea {
    overflow-y: inherit;
    overflow-x: inherit;
  }
  .signature-advise {
  .form-view-row {
    label {
      color:#262626;
      width:auto!important;
      min-width: auto;
    }
  }
  .nameAndAction {
    display:flex;
    .form-view-row {
      width:50%;
    }
  }
  .mt10 {
    margin-top:16px;
  }
}
</style>
